import http from '/util/http';
const plugin = requirePlugin('an_xin_zu');
import { uploadThirdInterfaceLog } from '/util/wuzhuUtil';
App({
  infoData: [],
  fromSource: 'applet',
  returnUrl: '',
  source: '',
  recordNo: '',
  signResult: null,
  result: null,
  orderNo: '',
  errMsg: '',
  onLaunch(options) {
    this.checkOptions(options)
  },
  onShow(options) {
    if (options && options.query) {
      //上传日志
      let data = this.checkOptions(options, true);
      console.log("checkOptions.data", data);
      this.uploadAXZReqLog("onShow", options.query, {},  1);
      //如果传入订单号一致时执行校验逻辑
      if (this.recordNo == data.recordNo) {
        if (this.signResult === false) {
          my.showToast({
            content: '签约失败，请返回重新发起签约',
          });
          this.signResult = null;
          this.goBack({
            success: this.signResult,
          });
          return;
        }
      }
      this.source = data.source;
      this.recordNo = data.recordNo;
      this.orderNo = data.orderNo;
      this.checkParams();
    }
  },
  checkOptions(options,isVerify) {
    my.showLoading({
      content: '签约处理中',
    });

    const { query } = options;

    if (!query) {
      my.hideLoading();
      my.showToast({
        content: '缺少必要参数',
      });
      this.errMsg = '缺少必要签约参数，请返回检查';
      return;
    }

    let data = query;

    if (query.params && typeof query.params === 'string') {
      data = JSON.parse(query.params);
    }

    if (data.env && data.env === 'test') {
      http._hoststr = 'https://woo.woozhu.cn';
      http._requestPath = '/wuzhu/';
    }
    if (!data.recordNo) {
      my.showToast({
        content: '缺少必要参数：recordNo',
      });
      return;
    }
    if (isVerify) {
      return data;
    }
    this.source = data.source;
    this.recordNo = data.recordNo;
    this.orderNo = data.orderNo;
  },
  checkParams() {
    let that=this;
    let reqData={ recordNo: this.recordNo};
    http.get('axz/queryWithholdSignDetail', reqData ).then((res) => {
      //保存请求日志
      that.uploadAXZReqLog("axz/queryWithholdSignDetail", reqData, res, res.code);
        if (!res || res.code !== '00' || !res.data) {
          my.showToast({
            content: res.msg || res.message,
          });
          this.errMsg = res.msg || res.message;
          this.goBack({
            success: this.signResult,
          });
          return;
        }

        if (!res.data.industryBizCoreSubMerchantUniqueCode) {
          my.showToast({
            content: '缺少必要参数：industryBizCoreSubMerchantUniqueCode',
          });
          return;
        }

        if (!res.data.partnerIds) {
          my.showToast({
            content: '缺少必要参数：partnerIds',
          });
          return;
        }

        if (!res.data.returnUrl) {
          my.showToast({
            content: '缺少必要参数：returnUrl',
          });
          return;
        }

        if (!res.data.externalAgreementNo) {
          my.showToast({
            content: '缺少必要参数：externalAgreementNo',
          });
          return;
        }

        this.setLog('第二步：掉查询接口：queryWithholdSignDetail接口返回信息');
        this.setLog('接口返回值：' + JSON.stringify(res.data));
        this.signContract(res.data);
      });
  },
  async signContract(signData) {
    const {
      industryBizCoreSubMerchantUniqueCode,
      notifyUrl,
      returnUrl,
      partnerIds,
      externalAgreementNo,
      merchantName,
      merchantServiceName,
      merchantServiceNameDesc,
    } = signData;

    const ICommonParams = {
      industryBizCoreSubMerchantUniqueCode, // 必填, 恒星团队给每个二级商户分配的,
      notifyUrl, // 支付宝服务器主动通知商户服务器里指定的⻚面 http/https 路径。建议商户使用 https, 选填
      returnUrl, // 支付宝App主动回跳商户App里指定的⻚面 http/https 路径。建议商户使用 https。
      partnerIds, // 必填，计收费签约pid列表 string
    };
    this.setLog('merchantName:' + merchantName);
    this.setLog('merchantServiceName:' + merchantServiceName);
    this.setLog('merchantServiceNameDesc:' + merchantServiceNameDesc);
    this.setLog('开始签约');

    const ISignParams = {
      externalAgreementNo, // 外部签约号，必填
      subMerchant: {
        merchantName, // 选填
        merchantServiceName, // 选填
        merchantServiceNameDesc, // 签约⻚服务详情，选填
      },
    };
    this.setLog('ISignParams  ： ' + JSON.stringify(ISignParams));
    this.setLog('commonParams  ： ' + JSON.stringify(ICommonParams));
    this.result = await plugin.sign(
      {
        signParams: ISignParams, // 签约参数,
        commonParams: ICommonParams, // 通用参数
      },
      true,
    );
    this.setLog('签约结果' + JSON.stringify(this.result));
    this.signResult = this.result.success;
    //保存请求日志
    this.uploadAXZReqLog("plugin.sign", ISignParams, this.result, this.signResult ? 1 : 2);
    this.returnUrl = returnUrl;
    // this.result = null
    my.showToast({
      content: this.signResult ? '签约成功，即将返回' : '取消签约，即将返回',
    });
    this.goBack({
      success: this.signResult,
    });
    my.hideLoading();
  },
   // 上传请求日志
   uploadAXZReqLog(reqUrl, req, res, status) {
    try {
      let params = {
        uniqueIdenty: 'my.axz:' + reqUrl,
        type: '11',
        requestParam: JSON.stringify(req),
        responseParam: JSON.stringify(res),
        status: status == '00' || status == 1 ? 1 : 2, // 状态：1成功2失败
        logSource: '0', // 请求发起来源 0:前端发起；1=后端发起
      };
      uploadThirdInterfaceLog(params);
    } catch (err) {
      console.log(err);
    }
  },

  setLog(info) {
    this.infoData.push(info);
  },
  goBack(result) {
    this.errMsg = '';
    if (this.source === this.fromSource) {
      this.goBackWuZhu(result);
      return;
    }
    this.goBackOtherMiniPro(result);
  },
  goBackWuZhu(result = {}) {
    this.setLog(result.success ? '签约成功' : '签约失败');
    my.navigateBackMiniProgram({
      extraData: {
        result: result.success ? 'success' : 'fail',
        orderNo: this.orderNo || '',
        returnUrl: this.returnUrl || '',
      },
    });
  },
  goBackOtherMiniPro(result = {}) {
    if (!this.returnUrl) {
      my.showToast({
        content: '缺少返回地址，请手动退出查看',
      });
      return;
    }
    const obj = {};
    const urlParams = this.returnUrl.split('?');
    const arr = urlParams && urlParams[1] ? urlParams[1].split('&') : [];
    arr.forEach((i) => {
      obj[i.split('=')[0]] = i.split('=')[1];
    });

    if (!obj.appId || !obj.page) {
      my.showToast({
        content: '缺少返回参数或地址，请手动退出查看',
      });
      return;
    }

    this.signResult = null;
    my.navigateToMiniProgram({
      appId: obj.appId, // 16 位
      path: obj.page,
      query: { result: result.success ? 'success' : 'fail', recordNo: this.recordNo || '' },
    });
  },
  goBackOtherApp(result) {
    my.redirectTo({
      url: '/pages/other/other?result=' + result.success,
    });
  },
});